<?php

namespace App\Http\Controllers\Personal;
use App\Facades\Site;
use App\Http\Requests\Common\Captcha\EmailSendRequest;
use App\Http\Requests\Common\Captcha\MobileRequest;
use App\Http\Requests\Common\Captcha\MobileSmsRequest;
use App\Http\Requests\Personal\ModPassword\ModPasswordTwoRequest;
use App\Http\Requests\Personal\MyResume\RegInfoCreateRequest;
use App\Models\Personal\PersonalLoginRecord;
use App\Models\Personal\PersonalUser;
use App\Http\Requests\Personal\ModPassword\ModPasswordRequest;
use App\Models\Personal\Resume;
use Illuminate\Http\Request;
use Style, Mail, Hash, Crypt,Sms,CustomPassword;


class PersonalUserController extends CommonController{
    /**
     * 账号设置
     * @param Request $request
     * @return mixed
     */
    public function setAccount(Request $request){
        $user = auth()->guard('personal')->user();
        //获取邮箱
        if (!empty($user->email)) {
            $list=explode('@', $user->email);
            $user->stremail = substr_replace($list[0],'****',2,4).(!empty($list[1])?'@'.$list[1]:'');
        } else {
            $user->stremail = '';
        }
        //获取手机
        if (!empty($user->mobile)) {
            $user->strmobile = substr_replace($user->mobile,'****',2,4);;
        } else {
            $user->strmobile = '';
        }
        return Style::view('personal.setAccount', compact('user'));
    }
    /**
     * 邮箱激活
     * @param Request $request
     * @return mixed
     */
    public function activationMail(Request $request){
        $user = PersonalUser::where('uid', $request->uid)->first(['uid', 'email', 'username']);
        $key = env('APP_KEY');
        $email = Crypt::decrypt($request->email);
        //验证绑定邮箱激活是不是成功
        if (Hash::check($user->uid . $user->username . $key, $request->key)) {
            $result = PersonalUser::where('uid', $user->uid)->update(['email_id' => 1, 'email' => $email]);
            if ($result) {
                return Style::view('personal.bindEmailSuccess', compact('user'));
            } else {
                return Style::view('personal.bindEmailError');
            }
        } else {
            return Style::view('personal.bindEmailError');
        }
    }
    /**
     * 邮箱发送
     * @param EmailSendRequest $request
     * @return mixed
     */
    public function emailSend(EmailSendRequest $request){
        $user = auth()->guard('personal')->user();
        $key = env('APP_KEY');
        $email = Crypt::encrypt($request->email);
        $user->mail_link = '?uid=' . $user->uid . '&email=' . $email . '&key=' . bcrypt($user->uid . $user->username . $key);

        if(!empty(Site::get('MailAddress'))){
            $result = Mail::send('emails.bind_email', ['user' => $user], function ($m) use ($request) {
                $m->from(Site::get('MailAddress'), Site::get('webname'));
                $m->to($request->email)->subject(Site::get('webname').'邮箱绑定');
            });
            return $result;
        }else{
            return false;
        }

    }
    /**
     * 获取短信验证码
     * @param MobileRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxJobCode(MobileRequest $request){
        $mobileNum = $request->input('mobile');
        $result = PersonalUser::where('mobile', $mobileNum)->where('mobile_id', 1)->first();
        if ($result) {
            return response()->json(['status' => '2', 'msg' => '此手机号码已经绑定']);
        } else {
            //设置session
            $request->session()->put('mobile_verification_code', rand(1000, 9999));
            $request->session()->put('mobile_verification', $mobileNum);
            //模板参数
            $smsParam = array(
                'product' => Site::get('webname'),
                'code'    => (string)session('mobile_verification_code')
            );
            $sendResult = Sms::codeSend($mobileNum, $smsParam);
            //返回对象
            if (is_object(@$sendResult->result) && $sendResult->result->err_code == '0') {
                return response()->json(['status' => '1', 'msg' => '发送短信成功']);
            } else {
                return response()->json(['status' => '0', 'msg' => '一分钟之内只能发一次,或者您发送的次数已经达到上限']);
            }
        }
    }
    /**
     * ajax验证短信验证
     * @param Request $request
     */
    public function ajaxJobSms(Request $request){
        $mcode = $request->input('mcode');
        $mobile = $request->input('mobile');
        //判断手机是不是被注册
        echo ($mcode == session('mobile_verification_code') && $mobile == session('mobile_verification') ) ? 'true' : 'false';
    }

    /**
     * 手机绑定
     * @param MobileSmsRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindMobile(MobileSmsRequest $request){
        $user = auth()->guard('personal')->user();
        //判断手机是不是被绑定了
        $personalUser = PersonalUser::where('mobile', $request->mobile)->where('uid','!=',$user->uid)->first();
        if($personalUser){
            return response()->json(['status' => 1,'msg' => '此手机号码已经被注册，不能绑定！']);
        }else{
            $result = PersonalUser::where('uid', $user->uid)->update(['mobile_id' => 1, 'mobile' => $request->mobile]);
            if($result){
                //删除验证码的session数据
                $request->session()->forget('mobile_verification');
                $request->session()->forget('mobile_verification_code');
                return response()->json(['status' => 0,'msg' => '手机绑定成功！']);
            }else{
                return response()->json(['status' => 1,'msg' => '手机绑定失败，请稍后重试！']);
            }
        }
    }

    /**
     * 取消QQ绑定
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancelBindQq(Request $request){
        $user = auth()->guard('personal')->user();
        if(!empty($user)){
            $result = PersonalUser::where('uid', $user->uid)->update(['qqopenid' => null,'updatetime'=>date('Y-m-d H:i:s',time())]);

            if($result){
                return response()->json(['status' => 0, 'msg' => '取消QQ绑定成功！']);
            }else{
                return response()->json(['status' => 1,'msg' => '取消QQ绑定失败，请稍后重试！']);
            }
        }else{
            return response()->json(['status' => 1, 'msg' => '取消QQ绑定失败！请稍后重试']);
        }
    }

    /**
     * 取消微信绑定
     * @param Request $request
     */
    public function cancel_wxbind(Request $request){
        $user = auth()->guard('personal')->user();
        if(!empty($user)){
            $result = PersonalUser::where('uid', $user->uid)->update(['wechatopenid' => null, 'wechatmpopenid' => null,
                'wechatunionid' => null,'updatetime'=>date('Y-m-d H:i:s',time())]);
            if($result){
                return response()->json(['status' => 0, 'msg' => '取消微信绑定成功！']);
            }else{
                return response()->json(['status' => 1, 'msg' => '取消微信绑定失败！']);
            }
        }else{
            return response()->json(['status' => 1, 'msg' => '取消微信绑定失败！请稍后重试']);
        }
    }


    //修改密码--------------------------------------------------------------------------------------------------------------
    /**
     * 修改密码
     * @param Request $request
     * @return mixed
     */
    public function modPassword(Request $request){
        $user = auth()->guard('personal')->user();
        $uid = $user->uid;
        return Style::view('personal.modPassword', compact('uid'));
    }

    /**
     * 修改密码ajax
     * @param Request $request
     */
    public function ajaxPass(Request $request){
        $user = auth()->guard('personal')->user();
        $password = PersonalUser::where('uid', $user->uid)->first(['password'])->password;
        //判断旧密码是不是正确
        echo (CustomPassword::check($request->input('oldpassword'),$password)) ? 'true' : 'false';
    }

    /**
     * 修改密码提交
     * @param ModPasswordRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function postModPassword(ModPasswordRequest $request){
        $user = auth()->guard('personal')->user();
        $input['password'] = CustomPassword::make($request->input('password'));
        PersonalUser::where('uid', $user->uid)->update($input);
        return redirect('personal/welcome');
    }


    /**
     * 注册用户简历信息
     * @param RegInfoCreateRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function regInfo(RegInfoCreateRequest $request){
        $userInput = $request->only(['mobile']);
        $rand = rand(100000, 999999);
        $userInput['password'] = CustomPassword::make($rand);
        $userInput['regtime'] = date('Y-m-d H:i:s', time());
        $userInput['updatetime'] = date('Y-m-d H:i:s', time());
        $userInput['last_login_time'] = date('Y-m-d H:i:s', time());
        $userInput['last_login_ip'] = getIp();
        //插入用户
        if($uid = PersonalUser::insertGetId($userInput)){
            $resumeInput = $request->only(['name', 'sex', 'birthday', 'education','mobile',
                'jobarea1', 'jobarea2', 'jobarea3', 'jobarea4', 'jobarea5',
                'jobsort1', 'jobsort2', 'jobsort3', 'jobsort4', 'jobsort5',
                'intentionjobs', 'introduction']);
            $resumeInput['uid'] = $uid;
            $resumeInput['default'] = 1;

            $resumeInput['language'] = 'cn';
            $resumeInput['regtime'] = date('Y-m-d H:i:s', time());
            $resumeInput['updatetime'] = date('Y-m-d H:i:s', time());
            //1代表先审核在显示简历
            $resumeInput['resume_status'] = (Site::get('resume_review') == '1') ? '0' : '1';
            $resumeInput['review'] = 0;//0代表未审核,1代表已处理
            $resumeInput['xs_status'] = 0;
            $result = Resume::create($resumeInput);

            if(!empty($request->mobile)){
                //删除验证码的session数据
                $request->session()->forget('mobile_verification');
                $request->session()->forget('mobile_verification_code');
            }
            //登录用户
            auth()->guard('personal')->loginUsingId($uid);

            //登录记录表
            $record = array();
            $record['uid'] = $uid;
            $record['personal_login_ip'] = getIp();
            $record['personal_login_time'] = date('Y-m-d H:i:s',time());
            $record['login_type'] = 1;
            $record['type'] = 1;
            //登录记录表
            PersonalLoginRecord::create($record);

            if($result){
                return response()->json(['status' => 0, 'mobile' => $request->mobile, 'rand' => $rand, 'uid' => $uid, 'webname' =>Site::get('webname')]);
            }else{
                return response()->json(['status' => 1, 'msg' => '注册简历失败！']);
            }
        }
    }

    /**
     * 修改新密码提交
     * @param ModPasswordRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function postModPasswordTwo(ModPasswordTwoRequest $request){
        $input = [];
        $user = auth()->guard('personal')->user();
        if(!empty($user)){
            $input['password'] = CustomPassword::make($request->input('password'));
            $result = PersonalUser::where('uid', $user->uid)->update($input);
            if($result){
                return response()->json(['status' => 0, 'password' => $request->password, 'mobile' => $request->mobile]);
            }else{
                return response()->json(['status' => 0, 'mobile' => '修改密码失败！']);
            }
        }
    }


}